package com.l024.framework.helper;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;

import androidx.core.content.FileProvider;
import androidx.loader.content.CursorLoader;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* @Author  wu_ming_zhi_bei
* @Date   2020/3/3 20:18
* @Notes  android7.0文件帮工具类
*/
public class FileHelper {
    private static volatile FileHelper fileHelper;
    private SimpleDateFormat simpleDateFormat;
    //相机返回码值=
    public static final int CAMEAR_REQUEST_CODE = 1004;
    //相册返回码值
    public static final int ALBUM_REQUEST_CODE = 1005;

    private FileHelper() {
        simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
    }

    public static FileHelper getInstance(){
        if(fileHelper==null){
            synchronized (FileHelper.class){
                if (fileHelper==null){
                    fileHelper = new FileHelper();
                }
            }
        }
        return fileHelper;
    }

    /**
     * 跳转到相机
     */
    private File tempFile = null;
    private Uri imgUri = null;
    public void toCamera(Activity activity){
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        String fileName = simpleDateFormat.format(new Date());
        tempFile = new File(Environment.getExternalStorageDirectory(),fileName+".jpg");
        //兼容android7.0
        if(Build.VERSION.SDK_INT<Build.VERSION_CODES.N){
            imgUri = Uri.fromFile(tempFile);
        }else{
            //利用FileProvider
            imgUri = FileProvider.getUriForFile(activity,activity.getPackageName()+".fileprovider",tempFile);
            //读写权限
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT,imgUri);
        activity.startActivityForResult(intent,CAMEAR_REQUEST_CODE);
    }

    /**
     * 跳转相册
     */
    public void toAlbum(Activity activity){
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        activity.startActivityForResult(intent,ALBUM_REQUEST_CODE);
    }

    /**
     *
     */
    public File getTempFile(){
        return tempFile;
    }

    /**
     * 根据Uri获取真实地址
     */
    public String getRealPathFromUrl(Context context,Uri uri){
        String[] proj = {MediaStore.Images.Media.DATA};
        CursorLoader cursorLoader = new CursorLoader(context, uri, proj, null, null, null);
        Cursor cursor = cursorLoader.loadInBackground();
        int index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(index);
    }
}
